//
//  SEGSelectCityView.m
//  SEGUhomeStandard
//
//  Created by 揭婧雯 on 2018/8/27.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGSelectCityView.h"

#import "SEGNewSelectCommunityCell.h"
#import "SEGSelectCommunityHeaderView.h"


@interface SEGSelectCityView () <UITableViewDelegate, UITableViewDataSource, SEGNewSelectCommunityCellDelegate>

/**
 列表
 */
@property (nonatomic, strong)UITableView *tableView;

/**
 热门城市标签
 */
@property (nonatomic, strong)UIView *hotCityView;


@property (nonatomic, strong)NSArray *codeArray;


/**
 城市列表数据源
 */
@property (nonatomic, strong)NSArray <NSArray *>*cityListArray;

/**
 城市列表首字母数组
 */
@property (nonatomic, strong)NSArray *cityPYArray;

@end


@implementation SEGSelectCityView
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setUpUI];
    }
    return self;
}

- (void)setUpUI
{
    [self addSubview:self.tableView];
    
    self.codeArray = @[@"340", @"218", @"158", @"75", @"257", @"138"];
    NSArray *tagsArray = @[@"深圳市", @"武汉市", @"长沙市", @"成都市", @"广州市", @"佛山市"];
    
    UIView *hotCityView = [[UIView alloc] initWithFrame:CGRectMake(15, 0, LYScreenWidth() - 15 - 30, 75)];
    hotCityView.backgroundColor = kColor_bg;
    CGFloat width = 85;
    CGFloat height = 30;
    CGFloat xPadding = (CGRectGetWidth(self.tableView.frame) - 45 - width * 3) / 2.0;
    CGFloat yPadding = 10;
    [tagsArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSInteger row = idx / 3;
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(15 + (idx % 3) * (width + xPadding), row * (height + yPadding), width, height)];
        button.backgroundColor = kColor_W;
        button.layer.masksToBounds = YES;
        button.layer.cornerRadius = 2;
        [button setTitle:obj forState:UIControlStateNormal];
        [button setTitleColor:kColor_1 forState:UIControlStateNormal];
        button.titleLabel.font = kFont_13;
        [hotCityView addSubview:button];
        button.tag = idx;
        [button addTarget:self action:@selector(seg_tagClick:) forControlEvents:UIControlEventTouchUpInside];
    }];
    self.hotCityView = hotCityView;
}

#pragma mark - UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2 + self.cityPYArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1) {
        return 0;
    }else {
        return self.cityListArray[section - 2].count;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SEGNewSelectCommunityCell* cell = [tableView dequeueReusableCellWithIdentifier:KSEGNewSelectCommunityCellIdentifier forIndexPath:indexPath];
    
    if (indexPath.section == 0) {
        [cell showCellWithType:SEGNewSelectCommunityCellType_CurrentCity cityName:self.currentCityName communityName:nil indexPath:indexPath];
    }else if (indexPath.section == 1) {
        
    }else {
        SEGCityListModel *model = self.cityListArray[indexPath.section - 2][indexPath.row];
        [cell showCellWithType:SEGNewSelectCommunityCellType_City cityName:model.name communityName:nil indexPath:indexPath];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0.01;
    }else if (section == 1) {
        return KSelectCommunityHeaderHeight;
    }else {
        return 31;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        return CGRectGetHeight(self.hotCityView.frame);
    }else {
        return 0.01;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section < 2) {
        return;
    }
    //选中城市
    SEGCityListModel *model = self.cityListArray[indexPath.section - 2][indexPath.row];
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectedCityWithCode:cityName:)]) {
        [self.delegate selectedCityWithCode:model.code cityName:model.name];
        self.hidden = YES;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return [UIView new];
    }
    
    SEGSelectCommunityHeaderView *headerView = [[SEGSelectCommunityHeaderView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), KSelectCommunityHeaderHeight)];
    headerView.backgroundColor = kColor_bg;
    if (section == 1) {
        headerView.type = SEGCommunityHeaderType_Center;
        headerView.text = @"热门城市";
    }else {
        headerView.type = SEGCommunityHeaderType_Center;
        headerView.text = self.cityPYArray[section - 2];
    }
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == 1) {
        //        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, CGRectGetHeight(self.hotCityView.frame))];
        //        footerView.backgroundColor = kColor_bg;
        //        [footerView addSubview:self.tagList];
        return self.hotCityView;
    }else {
        return [UIView new];
    }
}

//返回索引数组
-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView{
    return self.cityPYArray;
}

//索引列点击事件
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
    //点击索引，列表跳转到对应索引的行
    //    [SEGAlertView showTmepMessageWithMessage:title];
    [tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index + 2] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    return index + 2;
}

#pragma mark - 按钮等处理
- (void)seg_tagClick:(UIButton *)sender
{
    NSInteger idx = sender.tag;
    NSString *code = self.codeArray[idx];
    if (self.delegate && [self.delegate respondsToSelector:@selector(selectedCityWithCode:cityName:)]) {
        [self.delegate selectedCityWithCode:code cityName:sender.currentTitle];
        self.hidden = YES;
    }
}

#pragma mark - SEGNewSelectCommunityCellDelegate
- (void)locateButtonClicked
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(relocateAction)]) {
        [self.delegate relocateAction];
    }
}

#pragma mark - getter
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.bounds style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.sectionFooterHeight = 0;
        _tableView.backgroundColor = kColor_bg;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        _tableView.separatorInset = UIEdgeInsetsZero;
        _tableView.separatorColor = kColor_L2;
        _tableView.showsHorizontalScrollIndicator = NO;
        [_tableView registerClass:[SEGNewSelectCommunityCell class] forCellReuseIdentifier:KSEGNewSelectCommunityCellIdentifier];
        if(@available(iOS 11.0, *)){
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedSectionHeaderHeight  = _tableView.estimatedSectionHeaderHeight > 0 ? _tableView.estimatedSectionHeaderHeight : 0;
            _tableView.estimatedSectionFooterHeight  = _tableView.estimatedSectionFooterHeight > 0 ? _tableView.estimatedSectionFooterHeight : 0;
        }
        //设置索引列文本的颜色
        _tableView.sectionIndexColor = kColor_1;
        _tableView.sectionIndexBackgroundColor = [UIColor clearColor];
        //        _tableView.sectionIndexTrackingBackgroundColor = kColor_T;
    }
    return _tableView;
}

- (void)setCurrentCityName:(NSString *)currentCityName
{
    _currentCityName = currentCityName;
    [self.tableView reloadData];
}

- (void)setCityListModelArray:(NSArray<SEGCityListModel *> *)cityListModelArray
{
    NSMutableArray <NSMutableArray *>*titles = [NSMutableArray array];
    NSMutableArray *indexs = [NSMutableArray array];
    //先按拼音排序
    _cityListModelArray = [cityListModelArray sortedArrayUsingComparator:^NSComparisonResult(SEGCityListModel *obj1, SEGCityListModel *obj2) {
        return [obj1.pySname compare:obj2.pySname]; //升序
    }];
    //找出所有首字母
    [_cityListModelArray enumerateObjectsUsingBlock:^(SEGCityListModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *firstString = [[obj.pySname substringToIndex:1] uppercaseString];//转换为大写字母
        if (![indexs containsObject:firstString]) {
            [indexs addObject:firstString];
        }
    }];
    //找出所有首字母
    [indexs enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *arr = [NSMutableArray array];
        [_cityListModelArray enumerateObjectsUsingBlock:^(SEGCityListModel *model, NSUInteger idx2, BOOL * _Nonnull stop2) {
            NSString *firstString = [[model.pySname substringToIndex:1] uppercaseString];
            if ([obj isEqualToString:firstString]) {
                [arr addObject:model];
            }
        }];
        [titles addObject:arr];
    }];
    //    for(char c = 'A'; c <= 'Z'; c++ )
    //    {
    //        [indexs addObject:[NSString stringWithFormat:@"%c",c]];
    //        NSMutableArray *temp = [NSMutableArray array];
    //        for (int i = 0; i < 3; i ++) {
    //            SEGCityListModel *model = [[SEGCityListModel alloc] init];
    //            model.name = [NSString stringWithFormat:@"%c%d",c, i];
    //            model.code = [NSString stringWithFormat:@"%d", i];
    //            [temp addObject:model];
    //        }
    //        [titles addObject:temp];
    //    }
    self.cityPYArray = indexs;
    self.cityListArray = titles;
    [self.tableView reloadData];
}


@end
